package com.ruoyi.system.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.pingan.openbank.api.sdk.entity.SdkRequest;
import com.ruoyi.account.util.HttpResult;
import com.ruoyi.account.util.PaPayUtil;
import com.ruoyi.system.config.PayConfig;
import com.ruoyi.system.util.CodeEnum;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class BaseClient implements IBaseClient {


    @Override
    public HttpResult execute(JSONObject request) {
        PayConfig payConfig = SpringUtil.getBean(PayConfig.class);
        if (request.getString(PaPayUtil.CNSMR_SEQ_NO) == null || StrUtil.isEmpty(request.getString(PaPayUtil.CNSMR_SEQ_NO))) {
            request.put(PaPayUtil.CNSMR_SEQ_NO, PaPayUtil.getCnsmrSeqNo());
        }
        request.put("TxnClientNo", payConfig.getEcifNo());
        request.put("TxnTime", DateUtil.format(new Date(), "YYYYMMDDHHmmSS").concat("000"));
        request.put("MrchCode", payConfig.getMrchCode());
//        String logId = saveLog(request);
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName(getApiUrl());
        sdkRequest.setBody(request);

        HttpResult httpResult = new HttpResult();
        log.info("平安分账开始处理：{}", DateUtil.now());
        try {
            com.pingan.openbank.api.sdk.common.http.HttpResult h = PaPayUtil.getInstance().invoke(sdkRequest);
            httpResult.setStatus(CodeEnum.SUCCESS.getCode());
            httpResult.setBody(h.getData());
            if (h != null && h.getData() != null) {
//                saveResult(logId, h.getData());
            }
        } catch (Exception e) {
            httpResult.setStatus(CodeEnum.INTERNAL_SERVER_ERROR.getCode());
            httpResult.setError(e.getMessage());
//            saveResult(logId, e.getMessage());
        }
        log.info("平安分账结束处理：{}", DateUtil.now());
        return httpResult;
    }


    private Map<String, Object> toMap(Object entity) {
        try {
            Map<String, Object> map = new HashMap<>();
            Class<?> clazz = entity.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(entity));
            }
            return map;
        } catch (Exception e) {
            log.error("支付中心调用api参数转换异常:{}", e.getMessage());
        }
        return null;
    }

    public abstract String getApiUrl();

    public abstract void saveResult(String logId, String result);

    public abstract String saveLog(JSONObject params);
}
